﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using thousandclear.Data;
using thousandClear.Areas.Admin.Models;
using thousandClear.Util.Setting;
using System.Web.Routing;

namespace thousandClear.Areas.Shop.Controllers
{
    public class SignController : BaseController
    {
        // GET: Shop/Sign
        public ActionResult Index(string code, string state, string openid,string order,string good)
        {
            List<ProjectModel> list = new List<ProjectModel>();
            try
            {
                AppSetting setting = new AppSetting();

                string access_token = "";
                string UserName = "";
                string headimage = "";
                if (string.IsNullOrEmpty(openid))
                {
                    var i = GetOpenId(code);
                    openid = i.openid;
                    access_token = i.access_token;


                    if (string.IsNullOrEmpty(openid))
                    {
                        Response.Redirect(string.Format("https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxed78d8fdb0030e29&redirect_uri=http%3a%2f%2f{0}%2fshop%2fmain&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect", setting.AppDomainName.Replace("http://", "")));
                        return null;
                    }
                    var tt = GetUserInfo(openid, access_token);
                    headimage = tt.headimgurl;
                    UserName = tt.nickname;
                    UtilNS.Util.WriteLog("UserName::" + UserName);
                    UtilNS.Util.WriteLog("openid::" + openid);
                }
                ViewBag.order = order;
                using (var db = new qianjingEntities())
                {
                    var customer = db.O_Customer.FirstOrDefault(a => a.ocOpenid == openid);
                    if (customer == null)
                    {
                        db.O_Customer.Add(new O_Customer
                        {
                            ocOpenid = openid,
                            ocNicName = UserName,
                            CreatedDate = DateTime.Now,
                            ocHeadImage = headimage,
                            RowStatus = 1,
                            ocGrades = 0,
                        });
                        db.SaveChanges();

                    }
                    else
                    {
                        //customer.ocHeadImage = headimage;
                        //customer.ocNicName = UserName;
                        //db.SaveChanges();
                    }

                }
                ViewBag.OpenId = openid;
                ViewBag.State = state;
                ViewBag.Code = code;

                using (var db = new qianjingEntities())
                {
                    var records = db.D_item.OrderBy(a => a.DIMID).Where(a => (a.RowStatus == 1) && a.dimType == 1).ToList();
                    foreach (var item in records)
                    {
                        list.Add(new ProjectModel
                        {
                            dimDesc = item.dimDesc,
                            dimName = item.dimName,
                        });
                    }
                    var query = db.D_item.OrderBy(a => a.DIMID).Where(a => (a.RowStatus == 1 || a.RowStatus == 4) && a.dimType == 2).ToList();
                    ViewBag.T2 = query;
                    var Good = db.O_Goods.OrderBy(a => a.ogsType).ThenBy(a => a.ogsTimeMonth).ThenBy(a => a.ogsArea).Where(a => a.RowStatus == 1 && a.ogsType != 1).ToList();
                    if (!string.IsNullOrEmpty(good))
                    {
                        ViewBag.goodsMessage = Good[24];
                    }
                    else
                    {
                        ViewBag.goodsMessage = Good[0];
                    }


                }
                ViewBag.good = 0;
                if (!string.IsNullOrEmpty(good))
                {
                    ViewBag.good = good;

                }

                ViewBag.OpenId = openid;
            }
            catch (Exception ex)
            {
                Response.Redirect("https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx719afdb0aa0ebec4&redirect_uri=http%3a%2f%2fwww.qianjing-china.com%2fthousandclear%2fshop%2fSign&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect");
            }
            
            return View(list);
        }
        //HttpGet:Shop/Sign
        [HttpGet]
        public string selectType(int cardType, string area, int type)
        {
            string goodsMessage;
            using (var db = new qianjingEntities())
            {
                goodsMessage = JsonConvert.SerializeObject(db.O_Goods.FirstOrDefault(a => a.ogsTimeMonth == cardType & a.ogsArea == area & a.ogsType == type &a.CreatedBy== "meunItem"));
            }
            return goodsMessage;
        }

        // POST: Shop/Sign
        [HttpPost]
        public ActionResult Index(string data)
        {
            RouteValueDictionary dicgt = new RouteValueDictionary();
            try
            {
                AppSetting setting = new AppSetting();
                var post = JObject.Parse(data);
                string OGSID = post["OGSID"].Value<string>();
                string price = post["price"].Value<string>();
                string OpenId = post["OpenId"].Value<string>();
                int cardType = post["cardType"].Value<int>();
                int type = post["type"].Value<int>();
                int ogsSeqNum = post["ogsSeqNum"].Value<int>();
                string stringSelectModel = post["stringSelectModel"].Value<string>();
                string order = post["order"].Value<string>();
                UtilNS.Util.WriteLog("data" + JObject.Parse(data));


                string Number = DateTime.Now.ToString("yyMMddHHmmss");
                Random example = new Random();
                int Numradom = example.Next(10000, 99999);
                Number = Number + Numradom.ToString();

                using (var db = new qianjingEntities())
                {
                    var month = db.O_Goods.FirstOrDefault(a => a.OGSID.ToString() == OGSID);
                   
                    var toOCID = db.O_Customer.FirstOrDefault(a => a.ocOpenid == OpenId).OCID;
                    UtilNS.Util.WriteLog("toOCID" + toOCID);
                 
                    if (!string.IsNullOrEmpty(order))
                    {
                        
                        var orderDetail = db.v_Order.FirstOrDefault(a => a.toSerialNo == order);
                        //找到原来的签约产品
                        var ogsYuanlai = db.O_Goods.FirstOrDefault(oo => oo.OGSID == orderDetail.toOGID);
                        int ss = int.Parse(string.IsNullOrEmpty(orderDetail.CreatedBy) ? "0" : orderDetail.CreatedBy);
                        UtilNS.Util.WriteLog("xu yue ss:" + ss);
                        int shangyigechanpinzongshu = int.Parse(string.IsNullOrEmpty(orderDetail.UpdatedBy) ? "0" : orderDetail.UpdatedBy) + ogsYuanlai.ogsTime;
                        int zensong = (orderDetail.toZengSongLieji == null ? 0 : (int)orderDetail.toZengSongLieji) + (int)ogsYuanlai.ogsSeqNum;
                        UtilNS.Util.WriteLog("zensong:" + zensong);

                        db.T_Order.Add(new T_Order
                        {
                            toSerialNo = Number,
                            toSignTime = month.ogsSignTime,
                            //toTime = month.ogsSignTime * cardType + ogsSeqNum,
                            toTime = month.ogsTime + orderDetail.toTime,
                            toGoodNum = 1,
                            toOCID = Convert.ToInt16(toOCID),
                            toTotalRate = Convert.ToDecimal(price),
                            toOGID = Convert.ToInt16(OGSID),
                            RowStatus = 4,
                            CreatedDate = DateTime.Now,
                            toItemsGift = stringSelectModel,
                            toOAID = orderDetail.toOAID,
                            CreatedBy = (month.ogsSeqNum + ss).ToString(),
                            UpdatedBy = shangyigechanpinzongshu.ToString(),
                            toZengSongLieji = zensong,
                            toOATID = orderDetail.toOATID,
                            toRemark = orderDetail.toRemark
                        });
                        db.SaveChanges();
                    
                        string findday = orderDetail.osaEndDay.Substring(0, 4) + "-" + orderDetail.osaEndDay.Substring(4, 2) + "-" + orderDetail.osaEndDay.Substring(6, 2);
                        DateTime temp = DateTime.Parse(findday);
                        string startDay = temp.ToString("yyyyMMdd");
                        int zengsong = 0;
                        if (month.ogsTimeMonth > 1)
                        {
                            zengsong = (int)(((month.ogsTime - month.ogsTimeMonth * month.ogsSignTime) / month.ogsTimeMonth) < 0 ? 0 : ((month.ogsTime - month.ogsTimeMonth * month.ogsSignTime) / month.ogsTimeMonth));
                        }

                        if (month.ogsTimeMonth <= 1)
                        {
                            zengsong = 0;
                        }


                        using (var ty = new qianjingEntities())
                        {
                            string endDay = temp.AddMonths((zengsong + (int)month.ogsSignTime)).ToString("yyyyMMdd");
                            var top = ty.O_Address.FirstOrDefault(pp => pp.OASID == orderDetail.toOAID);

                            var orderDetail1 = ty.T_Order.FirstOrDefault(a => a.toSerialNo == Number);

                            top.osaEndDay = endDay;

                            orderDetail1.toParentID = order;

                            ty.SaveChanges();
                        }

                        dicgt.Add("openid", OpenId);
                        dicgt.Add("order", Number);

                      

                        return RedirectToAction("../Order/Index", dicgt);

                    }
                    db.T_Order.Add(new T_Order
                    {
                        toSerialNo = Number,
                        toSignTime = month.ogsSignTime,
                        toTime = month.ogsTime,
                        toGoodNum = 1,
                        toOCID = Convert.ToInt16(toOCID),
                        toTotalRate = Convert.ToDecimal(price),
                        toOGID = Convert.ToInt16(OGSID),
                        RowStatus = 0,
                        CreatedDate = DateTime.Now,
                        toItemsGift = stringSelectModel,
                        CreatedBy = month.ogsSeqNum.ToString()
                    });
                    UtilNS.Util.WriteLog("112212");
                    db.SaveChanges();
                }
                dicgt.Add("openid", OpenId);
                dicgt.Add("order", Number);
            }
            catch (Exception ex)
            {

            }

            
            return RedirectToAction("../Address/Index", dicgt);
        }

    }
}